<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>📸 后台图片管理器</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }

        .container {
            max-width: 1200px;
            margin: 0 auto;
            background: white;
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0,0,0,0.1);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #1e3a8f 0%, #3b82f6 100%);
            color: white;
            padding: 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
            font-weight: 700;
        }

        .header p {
            font-size: 1.1em;
            opacity: 0.9;
        }

        .stats-bar {
            background: #f8fafc;
            padding: 20px 30px;
            border-bottom: 1px solid #e2e8f0;
            display: flex;
            justify-content: space-around;
            align-items: center;
            flex-wrap: wrap;
            gap: 20px;
        }

        .stat-item {
            text-align: center;
        }

        .stat-number {
            font-size: 2em;
            font-weight: bold;
            color: #3b82f6;
            display: block;
        }

        .stat-label {
            color: #64748b;
            font-size: 0.9em;
            margin-top: 5px;
        }

        .upload-section {
            padding: 40px 30px;
            text-align: center;
            border-bottom: 1px solid #e2e8f0;
        }

        .upload-area {
            border: 3px dashed #cbd5e1;
            border-radius: 20px;
            padding: 60px 40px;
            margin: 20px 0;
            transition: all 0.3s ease;
            cursor: pointer;
            background: #f8fafc;
        }

        .upload-area:hover, .upload-area.dragover {
            border-color: #3b82f6;
            background: #eff6ff;
            transform: translateY(-2px);
        }

        .upload-icon {
            font-size: 4em;
            color: #94a3b8;
            margin-bottom: 20px;
        }

        .upload-text {
            font-size: 1.3em;
            color: #475569;
            margin-bottom: 10px;
            font-weight: 600;
        }

        .upload-hint {
            color: #64748b;
            font-size: 1em;
        }

        .file-input {
            display: none;
        }

        .btn {
            background: linear-gradient(135deg, #3b82f6 0%, #1e3a8f 100%);
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 25px;
            font-size: 1.1em;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            margin: 10px;
        }

        .btn:hover {
            transform: translateY(-2px);
            box-shadow: 0 10px 20px rgba(59, 130, 246, 0.3);
        }

        .btn-secondary {
            background: linear-gradient(135deg, #10b981 0%, #059669 100%);
        }

        .btn-danger {
            background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
        }

        .progress-bar {
            width: 100%;
            height: 8px;
            background: #e2e8f0;
            border-radius: 4px;
            overflow: hidden;
            margin: 20px 0;
            display: none;
        }

        .progress-fill {
            height: 100%;
            background: linear-gradient(90deg, #3b82f6 0%, #1e3a8f 100%);
            width: 0%;
            transition: width 0.3s ease;
        }

        .gallery-section {
            padding: 30px;
        }

        .section-title {
            font-size: 1.8em;
            color: #1e293b;
            margin-bottom: 20px;
            text-align: center;
            font-weight: 600;
        }

        .gallery-grid {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 20px;
        }

        .image-card {
            background: white;
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
            position: relative;
        }

        .image-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(0,0,0,0.15);
        }

        .image-preview {
            width: 100%;
            height: 200px;
            object-fit: cover;
            background: #f1f5f9;
        }

        .image-info {
            padding: 15px;
        }

        .image-name {
            font-weight: 600;
            color: #1e293b;
            margin-bottom: 5px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .image-meta {
            font-size: 0.9em;
            color: #64748b;
            margin-bottom: 3px;
        }

        .image-actions {
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }

        .btn-small {
            padding: 8px 15px;
            font-size: 0.9em;
            border-radius: 20px;
        }

        .loading {
            text-align: center;
            padding: 40px;
            color: #64748b;
        }

        .spinner {
            border: 3px solid #f3f4f6;
            border-top: 3px solid #3b82f6;
            border-radius: 50%;
            width: 40px;
            height: 40px;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .message {
            padding: 15px 20px;
            border-radius: 10px;
            margin: 20px 0;
            font-weight: 500;
            text-align: center;
        }

        .message.success {
            background: #dcfce7;
            color: #166534;
            border: 1px solid #bbf7d0;
        }

        .message.error {
            background: #fef2f2;
            color: #dc2626;
            border: 1px solid #fecaca;
        }

        .empty-state {
            text-align: center;
            padding: 60px 20px;
            color: #94a3b8;
        }

        .empty-icon {
            font-size: 4em;
            margin-bottom: 20px;
        }

        .empty-text {
            font-size: 1.2em;
            margin-bottom: 10px;
        }

        .empty-hint {
            color: #64748b;
        }

        @media (max-width: 768px) {
            .gallery-grid {
                grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
                gap: 15px;
            }
            
            .stats-bar {
                flex-direction: column;
                text-align: center;
            }
            
            .upload-area {
                padding: 40px 20px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>📸 后台图片管理器</h1>
            <p>智能上传 · 自动压缩 · 实时管理</p>
        </div>

        <div class="stats-bar" id="statsBar">
            <div class="stat-item">
                <span class="stat-number" id="totalImages">0</span>
                <div class="stat-label">总图片数</div>
            </div>
            <div class="stat-item">
                <span class="stat-number" id="totalSize">0 MB</span>
                <div class="stat-label">总大小</div>
            </div>
            <div class="stat-item">
                <span class="stat-number" id="lastUpload">--</span>
                <div class="stat-label">最后上传</div>
            </div>
        </div>

        <div class="upload-section">
            <div class="upload-area" id="uploadArea">
                <div class="upload-icon">📤</div>
                <div class="upload-text">拖拽图片到这里或点击上传</div>
                <div class="upload-hint">支持 JPG、PNG、GIF、WebP 格式，自动压缩优化</div>
            </div>
            
            <input type="file" id="fileInput" class="file-input" accept="image/*" multiple>
            
            <div class="progress-bar" id="progressBar">
                <div class="progress-fill" id="progressFill"></div>
            </div>
            
            <div id="messageArea"></div>
            
            <button class="btn" onclick="selectFiles()">📁 选择文件</button>
            <button class="btn btn-secondary" onclick="refreshGallery()">🔄 刷新图库</button>
        </div>

        <div class="gallery-section">
            <h2 class="section-title">🖼️ 图片库</h2>
            <div id="galleryContainer">
                <div class="loading">
                    <div class="spinner"></div>
                    <div>正在加载图片...</div>
                </div>
            </div>
        </div>
    </div>

    <script>
        class ImageManager {
            constructor() {
                this.apiBase = 'http://localhost:5000/api';
                this.images = [];
                this.init();
            }

            init() {
                this.setupEventListeners();
                this.loadGallery();
                this.loadStats();
            }

            setupEventListeners() {
                const uploadArea = document.getElementById('uploadArea');
                const fileInput = document.getElementById('fileInput');

                // 点击上传
                uploadArea.addEventListener('click', () => fileInput.click());

                // 文件选择
                fileInput.addEventListener('change', (e) => {
                    this.handleFileSelect(e.target.files);
                });

                // 拖拽上传
                uploadArea.addEventListener('dragover', (e) => {
                    e.preventDefault();
                    uploadArea.classList.add('dragover');
                });

                uploadArea.addEventListener('dragleave', () => {
                    uploadArea.classList.remove('dragover');
                });

                uploadArea.addEventListener('drop', (e) => {
                    e.preventDefault();
                    uploadArea.classList.remove('dragover');
                    this.handleFileSelect(e.dataTransfer.files);
                });
            }

            async handleFileSelect(files) {
                const validFiles = Array.from(files).filter(file => 
                    file.type.startsWith('image/')
                );

                if (validFiles.length === 0) {
                    this.showMessage('请选择有效的图片文件', 'error');
                    return;
                }

                this.showProgress(0);
                
                try {
                    for (let i = 0; i < validFiles.length; i++) {
                        await this.uploadImage(validFiles[i]);
                        this.showProgress((i + 1) / validFiles.length * 100);
                    }
                    
                    this.showMessage(`成功上传 ${validFiles.length} 张图片！`, 'success');
                    this.loadGallery();
                    this.loadStats();
                } catch (error) {
                    this.showMessage('上传失败: ' + error.message, 'error');
                } finally {
                    this.hideProgress();
                    document.getElementById('fileInput').value = '';
                }
            }

            async uploadImage(file) {
                const formData = new FormData();
                formData.append('image', file);

                const response = await fetch(`${this.apiBase}/upload`, {
                    method: 'POST',
                    body: formData
                });

                const result = await response.json();
                
                if (!response.ok) {
                    throw new Error(result.error || '上传失败');
                }

                return result;
            }

            async loadGallery() {
                try {
                    const response = await fetch(`${this.apiBase}/images`);
                    const result = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(result.error || '加载失败');
                    }

                    this.images = result.data;
                    this.renderGallery();
                } catch (error) {
                    this.showMessage('加载图片库失败: ' + error.message, 'error');
                    this.renderEmptyState();
                }
            }

            async loadStats() {
                try {
                    const response = await fetch(`${this.apiBase}/stats`);
                    const result = await response.json();
                    
                    if (response.ok) {
                        this.updateStats(result.data);
                    }
                } catch (error) {
                    console.error('加载统计失败:', error);
                }
            }

            renderGallery() {
                const container = document.getElementById('galleryContainer');
                
                if (this.images.length === 0) {
                    this.renderEmptyState();
                    return;
                }

                const galleryHTML = `
                    <div class="gallery-grid">
                        ${this.images.map(image => this.renderImageCard(image)).join('')}
                    </div>
                `;

                container.innerHTML = galleryHTML;
            }

            renderImageCard(image) {
                const uploadDate = new Date(image.upload_time).toLocaleString('zh-CN');
                return `
                    <div class="image-card">
                        <img src="http://localhost:5000${image.url}" 
                             alt="${image.original_name}" 
                             class="image-preview"
                             loading="lazy"
                             onclick="window.open('http://localhost:5000${image.url}', '_blank')">
                        <div class="image-info">
                            <div class="image-name" title="${image.original_name}">${image.original_name}</div>
                            <div class="image-meta">📊 ${this.formatFileSize(image.size)}</div>
                            <div class="image-meta">📅 ${uploadDate}</div>
                            <div class="image-actions">
                                <button class="btn btn-small btn-secondary" onclick="imageManager.viewImage('${image.url}')">
                                    👁️ 查看
                                </button>
                                <button class="btn btn-small btn-danger" onclick="imageManager.deleteImage('${image.filename}')">
                                    🗑️ 删除
                                </button>
                            </div>
                        </div>
                    </div>
                `;
            }

            renderEmptyState() {
                const container = document.getElementById('galleryContainer');
                container.innerHTML = `
                    <div class="empty-state">
                        <div class="empty-icon">📷</div>
                        <div class="empty-text">还没有上传任何图片</div>
                        <div class="empty-hint">点击上方上传区域添加您的第一张图片</div>
                    </div>
                `;
            }

            async deleteImage(filename) {
                if (!confirm('确定要删除这张图片吗？')) {
                    return;
                }

                try {
                    const response = await fetch(`${this.apiBase}/delete/${filename}`, {
                        method: 'DELETE'
                    });

                    const result = await response.json();
                    
                    if (!response.ok) {
                        throw new Error(result.error || '删除失败');
                    }

                    this.showMessage('删除成功！', 'success');
                    this.loadGallery();
                    this.loadStats();
                } catch (error) {
                    this.showMessage('删除失败: ' + error.message, 'error');
                }
            }

            viewImage(url) {
                window.open(`http://localhost:5000${url}`, '_blank');
            }

            updateStats(stats) {
                document.getElementById('totalImages').textContent = stats.total_images;
                document.getElementById('totalSize').textContent = stats.total_size_formatted;
                
                const lastUpload = stats.last_upload ? 
                    new Date(stats.last_upload).toLocaleDateString('zh-CN') : '--';
                document.getElementById('lastUpload').textContent = lastUpload;
            }

            formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
            }

            showProgress(percent) {
                const progressBar = document.getElementById('progressBar');
                const progressFill = document.getElementById('progressFill');
                
                progressBar.style.display = 'block';
                progressFill.style.width = percent + '%';
            }

            hideProgress() {
                const progressBar = document.getElementById('progressBar');
                setTimeout(() => {
                    progressBar.style.display = 'none';
                }, 500);
            }

            showMessage(text, type) {
                const messageArea = document.getElementById('messageArea');
                const message = document.createElement('div');
                message.className = `message ${type}`;
                message.textContent = text;
                
                messageArea.innerHTML = '';
                messageArea.appendChild(message);
                
                setTimeout(() => {
                    message.remove();
                }, 3000);
            }
        }

        // 全局函数
        function selectFiles() {
            document.getElementById('fileInput').click();
        }

        function refreshGallery() {
            imageManager.loadGallery();
            imageManager.loadStats();
        }

        // 初始化
        const imageManager = new ImageManager();

        // 页面加载完成提示
        window.addEventListener('load', () => {
            console.log('🚀 后台图片管理器已加载完成');
            console.log('📋 API 端点:', imageManager.apiBase);
        });
    </script>
</body>
</html>